package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

type Handler struct {
}

func (h *Handler) Ping(c *gin.Context) {
	c.JSON(200, gin.H{
		"message": "pong",
	})
}

func (h *Handler) Auth(c *gin.Context) {
	req := &AuthReq{}
	err := c.ShouldBindQuery(req)
	if err != nil {
		return
	}
	auths := GetAuthCache().Get(req.Secret)
	if auths == nil {
		c.JSON(http.StatusForbidden, gin.H{
			"message": "NOT_AUTHORIZED",
		})
		return
	}
	resAuth := []ResAuthorization{}
	for _, authone := range auths {
		permissions := []string{}
		if authone.Subscribe == "*" {
			permissions = append(permissions, "subscribe")
		}
		if authone.Publish == "*" {
			permissions = append(permissions, "publish")
		}
		resAuth = append(resAuth, ResAuthorization{
			Topic:       authone.Topic,
			Channels:    authone.Channels,
			Permissions: permissions,
		})
	}
	authResp := AuthResp{
		TTL:            TTL,
		Identity:       req.Secret,
		IdentityURL:    "http://localhost:8110",
		Authorizations: resAuth,
	}
	c.JSON(http.StatusOK, authResp)
}

func (h *Handler) Refresh(c *gin.Context) {
	GetAuthCache().Refresh()
}

func SetUpRouter(mode string) *gin.Engine {
	if mode == "release" {
		gin.SetMode(gin.ReleaseMode)
	}
	r := gin.Default()
	///r.Use(logger.GinLogger(), logger.GinRecovery(true), middlewares.Cors())
	handler := Handler{}
	r.GET("/ping", handler.Ping)
	r.GET("/auth", handler.Auth)
	r.GET("/refresh", handler.Refresh)
	return r
}
